<template>
    <div class="clearfix">
        <a-upload v-model:file-list="fileList" :action="action" multiple list-type="picture-card" :headers="headers"
            @preview="handlePreview" :accept="'.jpg, .jpeg, .icon, .png, .gif'" @remove="handleRemove"
            @change="handleChange" :before-upload="beforeUpload">
            <div v-if="fileList.length < 8">
                <plus-outlined />
                <div style="margin-top: 8px">Upload</div>
            </div>
        </a-upload>
        <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>
<script lang="ts" setup>
import type { UploadProps } from 'ant-design-vue';
import { isReactive } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
const props = defineProps({
    action: {
        type: String,
        default: "/api/admin/upload"
    },
    modelValue: {
        type: Array,
        default: []
    }
})
const headers = computed(() => {
  const user = JSON.parse(localStorage.getItem("__persisted__user") || "{}");
  return {
    Authorization: `Bearer ${user.token}`,
  };
});
const fileList = ref([])
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');
watch(() => props.modelValue, (newVal) => {
    if (newVal && newVal.length > 0) {
        fileList.value = newVal.map(item => {
            if (item) {
                let reg = new RegExp("(.*)(\\.(jpg|png|gif|jpeg))$")
                let name = item.match(reg)[1]
                return {
                    uid: Math.random().toString(36).substr(2, 9),
                    //正则找到文件名
                    name: name,
                    status: 'done',
                    url: item
                }
            }
        })
    }
}, {
    immediate: true
})
const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        message.error('Image must smaller than 10MB!');
    }
    return isJpgOrPng && isLt10M;
};

const emit = defineEmits(["update:modelValue"])
function getBase64(file: File) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
};
const handlePreview = async (file: UploadProps['fileList'][number]) => {
    if (!file.url && !file.preview) {
        file.preview = (await getBase64(file.originFileObj)) as string;
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
const baseUrl = `${import.meta.env.VITE_BASE_API_URL}/upload`;
// const ossUrl = import.meta.env.VITE_BASE_OSS_URL;
const handleChange = (info: UploadChangeParam) => {

    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        // getBase64(info.file.originFileObj, (base64Url: string) => {
        //     imageUrl.value = base64Url;
        //     loading.value = false;
        // });
        let isDone = info.fileList.every(item => {
            if (isReactive(item)) {
                if (item.status == "done") {
                    return true
                }
            } else {
                if (item.status == "done") {
                    return true
                }
            }
        })
        if (isDone) {
            console.log("info.fileList", info.fileList)
            let newFiles = info.fileList.map(item => {
                // 情况一、历史数据回显数据
                if (item.url) {

                    return item.url
                }
                // 情况二、上传成功
                if (isReactive(item)) {
                    //1-成功时，前面几个有data
                    if (item["response"]) {
                        if (item.response.data) {
                            return `${baseUrl}/${item.response.data}`
                        }
                        // 或者没有data,直接url
                        if (item.url) {
                            return item.url
                        }
                    }
                } else {
                    if (item.response) {
                        return `${baseUrl}/${item.response.data}`
                    }
                    return item.response ? `${baseUrl}/${item.response.data}` : ""
                }
            })
            console.log("newFiles", newFiles)
            emit("update:modelValue", newFiles);
        }

    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};
const handleRemove = (file: UploadFile) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
    emit("update:modelValue", newFileList.map(item => {
        if (isReactive(item)) {
            return item.url
        } else {
            return item.response ? baseUrl + "/upload/" + item.response.data : ""
        }
    }));
}

</script>
<style scoped>
.ant-upload {
    width: 200px !important;
    height: 200px !important;
}

.ant-upload-select {
    width: 200px !important;
    height: 200px !important;
}

.ant-upload-select-picture-card {
    width: 200px !important;
    height: 200px !important;
}

.ant-upload-list-item-container {
    width: 200px !important;
    height: 200px !important;
}
</style>